<template>

  <Teleport to="#app" v-if="payModalShow">
    <div class="penment_bck">

      <div class="payType">
        <div class="close"><span @click="handleClose">X</span></div>
        <div class="payType-title" v-if="state.status ==10">
          <p> 请选择支付方式</p>
          <ul class="payType-title-list">
            <li v-for="item in payChangeList"
              :class="item.value == payChange ? (item.value == 1 ? 'activeBule' :'activeGreen' ): '' " :key="item.value"
              @click="changeType(item.value)">
              <img :src="item.img" alt="">
              <span>{{ item.name }}</span>
            </li>
            <!-- <li>
              <img src="../../assets/img/pay/WeChat.png" alt="">
              <span>
                微信
              </span>
            </li> -->
          </ul>
        </div>
        <div class=" payType-content" v-if="state.status == 10">
          <img   class="qrCdoe" :src="payChange==1? payCode.AlicodeUrl :payCode.WxcodeUrl" alt="">
          <ul class="OrderInfo">
            <li>
              <div>订单号 : {{ payCode.OuderId}}</div>
              <div>当前状态:{{ ouderStatus(state.status) }}</div>
              <div>付款倒计时 : {{ state.mmssTimer }}</div>
            </li>
            <li class="price">
              <p>
                <!-- $199 -->
                ￥{{ price }}
              </p>
              <s>
                <!-- $199 -->￥{{ price }}
              </s>
            </li>
            <li class="UserAgreement">
              <span>
                请使用{{ payChange == 1 ? '支付宝': '微信' }}支付,充值即代表同意《
                <span class="UserAgreementBtn">
                  鹿线AI用户协议
                </span>
                》
              </span>
            </li>
          </ul>
        </div>
        <div v-if="state.status !==10 " class="payOk">
          <p>当前订单{{ ouderStatus(state.status) }}</p>
          <button @click="handleClose">返回商品页</button>
        </div>
      </div>
    </div>
  </Teleport>



</template>
<script lang='ts' setup>
import { defineProps, defineEmits, ref, watchEffect, watch, reactive, onBeforeUnmount, onMounted } from 'vue'
import {  aliPay, wxPay, checkOuder } from '@/api/account';
import AliImg from '@/assets/img/pay/Alipay.png'
import WxImg from '@/assets/img/pay/WeChat.png'
import QRCode  from 'qrcode'; //引入生成二维码插件
import { ouderStatus } from '@/hooks/account'


const props = defineProps({
  // 商品id
  orderInfo: {
    type:Number,
    default:''
  },
  //订单金额
  price:{
    type: Number,
    default:0
  },
  // 是否显示弹窗
  payModalShow:{
    type:Boolean,
    default:false
  }
})


// 事件处理器  关闭窗口
const emit = defineEmits(['close','payOk','payout'])
function handleClose() {
  clearInterval(paymentTimer.value)
  paymentTimer.value = null
  emit('close') // 发射 close 事件  
}  

const payCode = ref({
  OuderId: '', //订单号都是一个 就看用哪个付款方式
  AlicodeUrl: '' ,
  WxcodeUrl:'',
}); 
const getQRcode = (codeType:string,url:string)=>{
  
  if(url){
    QRCode.toDataURL(url,(error:any,dataURL:string)=>{
      if (error) {
        console.log(error)
        return
      }
      codeType =='wx'?(payCode.value.WxcodeUrl = dataURL):(payCode.value.AlicodeUrl = dataURL)
    })
  }
console.log(payCode.value);

}

// 微信和支付宝支付 切换等
const payChangeList = ref([
  { name: '微信支付', value: 2, img: WxImg , },
  { name: '支付宝支付', value: 1, img: AliImg, }
])
const payChange = ref(1)
// 有url 在过期前无需二次请求, 直接打断

const changeType = async (value:number)=>{
  payChange.value = value
  // if (payCode.value.OuderId == props.orderInfo.id) return
  // console.log('切换后再执行', payCode.value.OuderId, props.orderInfo.id);
  // if (value === 2 && payCode.value.AlicodeUrl === '') AlipayMen() ;
  // if (value === 1 && payCode.value.WxcodeUrl === '') WXpayMen();
  // newTimeFun();
  console.log('切换后', payCode.value);
  
  if (value === 2 && payCode.value.WxcodeUrl == ''){
    console.log('执行微信支付执行切换');
    await WXpayMen()

  }
  if(value === 1 && payCode.value.AlicodeUrl == ''){
    console.log('执行AliPay支付执行切换');
    console.log(payCode.value.AlicodeUrl == '');
    await AlipayMen()

  }

}

//10分钟内 每个套餐的订单号是一致的(改变套餐 再回来 10分钟内事一样的订单) 所以不用每次都请求
const AlipayMen = async ()=>{
  let res =  await aliPay(props.orderInfo)
  // console.log('ali',res);
    payCode.value.OuderId = res.data.orderNo
    getQRcode('ali',res.data.codeUrl)  
  return res.data.orderNo
}

const WXpayMen =async () => {
  let res =  await wxPay(props.orderInfo)
  // console.log('wx',res);
  payCode.value.OuderId = res.data.orderNo
  getQRcode('wx',res.data.codeUrl)
  return res.data.orderNo
}

// 倒计时
const state = reactive({
 mmssTimer:'',
  timer: 600000,
  active: false,
  status: 10 ,//状态
  timerIs: null as any
})

// 时间函数 格式化时间  这里需要定时器
const tiemtStr = (outstrTime:number)=>{

    const now = new Date().getTime();
    const diff = outstrTime - now;
    console.log(diff);

    if (diff <= 0) {
      state.mmssTimer = '00分00秒';
      state.active = false;
    }else{
      const minutes = Math.floor(diff / (60 * 1000));
      const seconds = Math.floor((diff % (60 * 1000)) / 1000);
      state.mmssTimer = `${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}秒`;
    }
    

    // return `${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}秒`;
}

// 查询订单状态   NO1830572365429559297   createTime: "2024-09-02T19:43:57"
const checkOuderAPI = async(ouderId?:string|number)=>{
  // if(payCode.value.OuderId){
  //   console.log('请求订单号',payCode.value.OuderId)
  // }
  console.log('接口付款状态请求的次数', payStartSummary.value /6)

  let id = ouderId || payCode.value.OuderId
  if(id === undefined) return console.log('没有订单号')
  const res = await checkOuder(id as string)
// console.log('查询订单',res);

//   console.log('首次的状态1', (res.data != null), (state.active),(state.active == false));
//   console.log('首次的状态2', (res.data != null && state.active== false));
  
  // 查到订单生成时间 +10分钟 就是倒计时时间
  if (res.data && state.active == false){
    let outTime = new Date(res.data.createTime).getTime()
    // console.log('首次计时时间戳',outTime)
    state.timer = outTime + (1000 *10 *60)
    // console.log('设置时间戳', state.timer, state.timer - outTime);
    state.active = true; // 激活倒计时  
    // console.log('设置时间成功');
  }
  console.log(res);
  state.status = res.data.status  // 更新订单状态  
  //状态不是未付款 , 清除一切 定时器 图片 订单信息等
if(res.data.status  !== 10 ){
  resetAll()
}
}
//轮询订单状态
//计数器  优化 请求频率
const payStartSummary = ref(0);
const paymentTimer = ref<NodeJS.Timeout | null>(null);
const newTimeFun =  () => {
  if (paymentTimer.value !== null){
    console.log('清除定时器首次');
    clearInterval(paymentTimer.value)
    paymentTimer.value = null
  }
  paymentTimer.value = setInterval(  ()=>{
    // if (payStartSummary.value % 3 == 0) {
    // }
    payStartSummary.value++

    if (payStartSummary.value %6 ==0 || payStartSummary.value >=596 ){
      console.log('请求订单状态', payStartSummary.value);
      checkOuderAPI()
    }
    // state.timer = state.timer -  1000 因为算的是当前时间差 已经减了1秒
    // console.log('倒计时每次更新',state.timer /1000);
        tiemtStr(state.timer)
    if (state.active == false){
        clearInterval(paymentTimer.value)
      paymentTimer.value = null
      state.status = 30
      // state.timer==0;
      // state.active = false
      payStartSummary.value == 0;
    }else{
      // state.active = true 
    }

  }, 1000)
}





// 这个要放最下面  太难用了 如果数据变化 甚至会打断定时器的销毁
// watchEffect(() => {
//   // console.log('paytype',props.orderInfo);
//   // AlipayMen()  //会一直报错
//   if (props.orderInfo){
//     console.log('触发响应执行');
//     changeType(1);
//     newTimeFun();
//   }

// })
// watchEffect(()=>{
//   console.log('watchEffect');

//   if (payCode.value.OuderId) {
//     console.log('watchEffect');
//     changeType(1);
//     newTimeFun()
//   }
// })
// watch(() => props.orderInfo, (newvalue, oldvalue) => {
//   console.log(`orderInfo 改变了: ${oldvalue} -> ${newvalue}`);
// })

//从返回值来看   changeType 有时候比 newTimeFun 慢 导致没返回订单号   查询订单失败 
// watch(() => props.payModalShow,async (newvalue,oldvalue)=>{
//   // console.log(`orderInfo 改变了: ${oldvalue.id} -> ${newvalue.id}`);
//   //   await  changeType(1);
//   // newTimeFun();
// })

onMounted(async () => {
  if (props.orderInfo) {
   let id =   await changeType(1);
    await checkOuderAPI(id) //查询订单的时间为主
     newTimeFun();  //轮询订单的状态为主
  }
});

// 重置所有状态
const resetAll = () => {
  state.active = false
  payCode.value.AlicodeUrl == '';
  payCode.value.WxcodeUrl == ''
  clearInterval(state.timerIs);
  state.timerIs = null;
  clearInterval(paymentTimer.value)
  paymentTimer.value = null
}


onBeforeUnmount(()=>{
  resetAll() 
})

</script>
<style scoped lang='scss'>

.penment_bck{
  transform: translateZ(0);
  position: absolute;
  top: 0;
  background-color: rgba($color: #000000, $alpha: .5);
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}


.payType{
  padding: 93px 74px;
  background-color: #fff;
 width: 883px;
  height: 623px;
  background: #FFFFFF;
  border-radius: 40px 40px 40px 40px;
  box-sizing: border-box;
}
.payOk{
  
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
align-items: center;
p {
    text-align: center;
    font-size: 32px;
    font-weight: 700;
  margin: 20px auto;
  }
  button{
    width: 150px;
    height: 50px;
    color: #fff;
    font-size: 18px;
    text-shadow: 2px 2px 2px 2px gray;
    background-color: #1296DB;
    cursor: pointer;
    border: 1.5px solid gray;
    border-radius: 4px;
    box-shadow: 0px 0px 1px 1px gray;
  }
}


.close{
  text-align: right;
  cursor: pointer;
}
.payType-title{
  font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 32px;
    color: #232323;
    width: 100%;
    p{
      margin-bottom: 20px;
    }
}

.payType-title-list{
  display: flex;
  justify-content: space-between;
  width: 100%;

  li{

    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 14px 14px 14px 14px;
    width: 305px;
    height: 103px;
    text-align: center;
    border: 2px solid rgba($color: #000000, $alpha: .2);
    box-sizing: border-box;
    cursor: pointer;
            img {
                width: 36px;
                height: 36px;
                margin-right: 20px;
              }
  }

    
.activeBule {
  border: 2px solid #1296DB;
}
.activeGreen {
  border: 2px solid rgb(40, 196, 69);
}
}

.payType-content{
    display: flex;
    margin-top: 53px;
  .qrCdoe{
      width: 232px;
        height: 241px;
        border-radius: 14px 14px 14px 14px;
        border: 1px solid #E0E0E0;
        margin: 6px 5px 4px 14px
  }

  .OrderInfo{

    display: flex;
    flex-direction: column;
    padding-top: 20px ;
    padding-left: 25px;
    li {
      div {
          font-family: Microsoft YaHei, Microsoft YaHei;
          font-weight: 400;
          font-size: 18px;
          color: gray;
          margin-bottom: 20px
        }
    }
  }
.price{
  flex: 1;
  display: flex;
  align-items: baseline;
  font-family: Microsoft YaHei, Microsoft YaHei;
  // margin: 0px 0 0 30px;
      p{
        font-weight: bold;
          font-size: 58px;
          color: #232323; 
      }
      s{
        font-weight: 400;
          font-size: 28px;
          color: #BFBFBF;
      }
}
.UserAgreement{
  font-weight: 400;
    font-size: 18px;
    color: #232323;

    .UserAgreementBtn{
      color: #c90000;
      cursor: pointer;
    }
}
}


</style>
